package com.cssy.yd.logic.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.yd.logic.dao.LogicPoDAO;
import com.cssy.yd.logic.dao.LogicPoItemDAO;
import com.cssy.yd.logic.dao.LogicPoReturnDAO;
import com.cssy.yd.logic.dao.LogicPoReturnItemBatchDAO;
import com.cssy.yd.logic.dao.LogicPoReturnItemDAO;
import com.cssy.yd.logic.dao.LogicPoWareDAO;
import com.cssy.yd.logic.dao.LogicPoWareItemBatchDAO;
import com.cssy.yd.logic.dao.LogicPoWareItemDAO;
import com.cssy.yd.logic.entity.LogicPoDO;
import com.cssy.yd.logic.entity.LogicPoItemDO;
import com.cssy.yd.logic.entity.LogicPoReturnDO;
import com.cssy.yd.logic.entity.LogicPoReturnItemBatchDO;
import com.cssy.yd.logic.entity.LogicPoReturnItemDO;
import com.cssy.yd.logic.entity.LogicPoWareDO;
import com.cssy.yd.logic.entity.LogicPoWareItemBatchDO;
import com.cssy.yd.logic.entity.LogicPoWareItemDO;
import com.cssy.yd.logic.entity.LogicWhAffDO;
import com.cssy.yd.logic.service.ILogicPoReturnService;
import com.cssy.yd.logic.service.ILogicWhAffStockService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.exception.SyCodeException;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicPoReturnService")
public class LogicPoReturnServiceImpl implements ILogicPoReturnService{
	@Resource(name = "logicPoReturnDAO")
	private LogicPoReturnDAO logicPoReturnDAO;
	
	@Resource(name = "logicPoWareItemDAO")
	private LogicPoWareItemDAO logicPoPoWareItemDAO;
	
	@Resource(name = "logicPoWareDAO")
	private LogicPoWareDAO logicPoWareDAO;
	
	@Resource(name = "logicPoReturnItemDAO")
	private LogicPoReturnItemDAO logicPoReturnItemDAO;
	
	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Resource(name = "logicWhAffStockService")
	private ILogicWhAffStockService logicWhAffStockService;
	
	@Resource(name = "logicPoDAO")
	LogicPoDAO logicPoDAO;
	
	@Resource(name = "logicPoItemDAO")
	LogicPoItemDAO logicPoItemDAO;
	
	@Resource(name="logicPoReturnItemBatchDAO")
	LogicPoReturnItemBatchDAO logicPoReturnItemBatchDAO;
	
	@Resource(name="logicPoWareItemBatchDAO")
	private LogicPoWareItemBatchDAO logicPoWareItemBatchDAO;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicPoReturnDO>  list=logicPoReturnDAO.find(scs);
		rs.setRecordCount(logicPoReturnDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		Integer i =logicPoReturnDAO.deleteLogicPoReturnDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer update(LogicPoReturnDO t, User user) throws SyBaseException {
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		return logicPoReturnDAO.updateLogicPoReturnDO(t);
	}

	@Override
	public LogicPoReturnDO save(LogicPoReturnDO t, User user) throws SyBaseException {
		t.setDcruser(user.getName());
		t.setDctime(new Date());
		t.setId(IDCodeTypeUtil.getId());
		logicPoReturnDAO.insertLogicPoReturnDO(t);
		return t;
	}

	@Override
	public LogicPoReturnDO findListById(String id) throws SyBaseException {
		return logicPoReturnDAO.findLogicPoReturnDOByPrimaryKey(id);
	}
	
	@Override
	public SearchResult findItemListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs=new SearchResult(scs);
		List<LogicPoReturnItemDO>  list=logicPoReturnItemDAO.find(scs);
		rs.setRecordCount(logicPoReturnItemDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer deleteItem(String id) throws SyBaseException {
		Integer i =logicPoReturnItemDAO.deleteLogicPoReturnItemDOByPrimaryKey(id);
		return null;
	}

	@Override
	public Integer updateItem(LogicPoReturnItemDO t) throws SyBaseException {
		return logicPoReturnItemDAO.updateLogicPoReturnItemDO(t);
	}

	@Override
	public LogicPoReturnItemDO saveItem(LogicPoReturnItemDO t) throws SyBaseException {
		t.setId(IDCodeTypeUtil.getId());
		logicPoReturnItemDAO.insertLogicPoReturnItemDO(t);
		return t;
	}

	@Override
	public LogicPoReturnItemDO findItemListById(String id) throws SyBaseException {
		return logicPoReturnItemDAO.findLogicPoReturnItemDOByPrimaryKey(id);
	}

	@Override
	public List<LogicPoReturnItemDO> findItemListBypoId(String id)
			throws SyBaseException {
		return null;
	}

	

	@Override
	public void returnsave(HttpServletRequest request, LogicPoReturnDO curAP)
			throws SyBaseException, SyCodeException {
		try {
			String itemdata = request.getParameter("itemdata");
			String type = request.getParameter("type");
			String bhid = request.getParameter("id");
			
			List<LogicPoReturnItemDO> axxlist=JSONArray.parseArray(itemdata, LogicPoReturnItemDO.class);
			if("bh".equals(type)){
				LogicPoReturnDO lReturnDO = logicPoReturnDAO.findLogicPoReturnDOByPrimaryKey(bhid);
				lReturnDO.setBillstatus((short)0);
				this.update(lReturnDO,  SessionUtil.getUser(request));
			}else{
				curAP.setBillstatus(Short.parseShort(type));
				if (curAP.getId() != null && !"".equals(curAP.getId())) {// 修改
					curAP.setDuuser(SessionUtil.getUser(request).getName());
					curAP.setDutime(new Date());
					logicPoReturnDAO.updateLogicPoReturnDO(curAP);
					String itemdelete = request.getParameter("itemdelete");
					if(itemdelete!=null&&!"".equals(itemdelete)){
						List<LogicPoReturnItemDO> lp=JSONArray.parseArray(itemdelete, LogicPoReturnItemDO.class);
						for(int i=0;i<lp.size();i++){
							if(lp.get(i).getId()!=null && !"".equals(lp.get(i).getId())){
								logicPoReturnItemDAO.deleteLogicPoReturnItemDOByPrimaryKey(lp.get(i).getId());
							}
						}
					}
					for(int i=0;i<axxlist.size();i++){
						axxlist.get(i).setReturnpoid(curAP.getId());
						if(axxlist.get(i).getId()!=null && !"".equals(axxlist.get(i).getId())){
							logicPoReturnItemDAO.updateLogicPoReturnItemDO(axxlist.get(i));
						}
//						else{
//							axxlist.get(i).setId(IDCodeTypeUtil.getId());
//							logicPoReturnItemDAO.insertLogicPoReturnItemDO(axxlist.get(i));
//						}
//						SearchConditions scs = new SearchConditions();
//						scs.setRemovedProperty(null);
//						scs.setLimitPage(false);
//						scs.addCondition("", axxlist.get(i).getId(), comp)
						logicPoReturnItemBatchDAO.deleteByreturnItemId(axxlist.get(i).getId());
						if(axxlist.get(i).getItemBatch() !=null  && !"".equals(axxlist.get(i).getItemBatch())){
							List<LogicPoReturnItemBatchDO> itemBatchDOs=JSONArray.parseArray(axxlist.get(i).getItemBatch(), LogicPoReturnItemBatchDO.class);
							if(itemBatchDOs != null && itemBatchDOs.size()>0){
								for (int j = 0; j < itemBatchDOs.size(); j++) {
									itemBatchDOs.get(j).setId(IDCodeTypeUtil.getId());
									itemBatchDOs.get(j).setReturnitemid(axxlist.get(i).getId());
									logicPoReturnItemBatchDAO.insertLogicPoReturnItemBatchDO(itemBatchDOs.get(j));
								}
							}
						}
						
						}
				} else {// 新增
					String id=IDCodeTypeUtil.getId();
					curAP.setPaymentstatus(0);
					curAP.setReturnpocode(syCodeService.getCode("CT","CT",SyCode.DATE_YYMM,5));
					curAP.setBillstatus(Short.parseShort("0"));
					curAP.setBilltype((long) 1);
					curAP.setId(id);
					curAP.setDcruser(SessionUtil.getUser(request).getName());
					curAP.setDctime(new Date());
					curAP.setThrq(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("thrq")));
					logicPoReturnDAO.insertLogicPoReturnDO(curAP);
					for(int i=0;i<axxlist.size();i++){
						String itemId = IDCodeTypeUtil.getId();
						axxlist.get(i).setReturnpoid(id);
						axxlist.get(i).setId(itemId);
						logicPoReturnItemDAO.insertLogicPoReturnItemDO(axxlist.get(i));
						if(axxlist.get(i).getItemBatch() !=null  && !"".equals(axxlist.get(i).getItemBatch())){
							List<LogicPoReturnItemBatchDO> itemBatchDOs=JSONArray.parseArray(axxlist.get(i).getItemBatch(), LogicPoReturnItemBatchDO.class);
							if(itemBatchDOs != null && itemBatchDOs.size()>0){
								for (int j = 0; j < itemBatchDOs.size(); j++) {
									itemBatchDOs.get(j).setId(IDCodeTypeUtil.getId());
									itemBatchDOs.get(j).setReturnitemid(itemId);
									logicPoReturnItemBatchDAO.insertLogicPoReturnItemBatchDO(itemBatchDOs.get(j));
								}
							}
						}
					}
				}
				if("3".equals(type)){
				for (int k = 0; k < axxlist.size(); k++) {
				LogicPoReturnItemDO lItemDO =  logicPoReturnItemDAO.findLogicPoReturnItemDOByPrimaryKey(axxlist.get(k).getId());
				//System.out.println("之前..........:"+lItemDO.getBadcount()+"第二个:"+lItemDO.getJbadCount());
				lItemDO.setBadcount((lItemDO.getBadcount()==null?0.0:lItemDO.getBadcount())+(axxlist.get(k).getReturnquantity()==null?0.0:axxlist.get(k).getReturnquantity()));
				lItemDO.setJbadCount((lItemDO.getJbadCount()==null?0.0:lItemDO.getJbadCount())+(axxlist.get(k).getJreturnquantity()==null?0.0:axxlist.get(k).getJreturnquantity()));
				SearchConditions scs = new SearchConditions();
				scs.addCondition("powarecode",curAP.getPowarecode(),SearchCondition.OP_EQUAL);
				List<LogicPoWareDO> lpwlist=logicPoWareDAO.find(scs);
				
				SearchConditions scs1 = new SearchConditions();
				scs1.setRemovedProperty(null);
				scs1.setLimitPage(false);
				scs1.addCondition("powareid",lpwlist.get(0)!=null?lpwlist.get(0).getId():"",SearchCondition.OP_EQUAL);
				List<LogicPoWareItemDO> lpwitem=logicPoPoWareItemDAO.find(scs1);
				
				
				
				
				SearchConditions scs2 = new SearchConditions();
				scs2.addCondition("pocode",curAP.getPocode(),SearchCondition.OP_EQUAL);
				List<LogicPoDO> poList=logicPoDAO.find(scs2);
				
				SearchConditions scs3 = new SearchConditions();
				scs3.setRemovedProperty(null);
				scs3.setLimitPage(false);
				scs3.addCondition("po_id",poList.get(0)!=null?poList.get(0).getId():"",SearchCondition.OP_EQUAL);
				List<LogicPoItemDO> poItem=logicPoItemDAO.find(scs3);
				
				boolean billstatus=true;
				if(lpwitem.size()>0){
					for(int i=0;i<lpwitem.size();i++){
							if(lpwitem.get(i).getMaterialsid().equals(lItemDO.getMaterialsid())&&lpwitem.get(i).getCode().equals(lItemDO.getCode())&&lpwitem.get(i).getName().equals(lItemDO.getName())){
								if((lpwitem.get(i).getJquantity()!=null?lpwitem.get(i).getJquantity():0)<lItemDO.getJbadCount()){
									throw new SyBaseException("错误:当前退货数量大于入库数量");
								}else{
									if(poItem.size()>0){
										for (int j = 0; j < poItem.size(); j++) {
											if(poItem.get(j).getMaterialsid().equals(lItemDO.getMaterialsid())&&poItem.get(j).getCode().equals(lItemDO.getCode())&&poItem.get(j).getName().equals(lItemDO.getName())){
												poItem.get(j).setReturnJquantity((poItem.get(j).getReturnJquantity()==null?0:poItem.get(j).getReturnJquantity())+(axxlist.get(k).getReturnquantity()!=null?axxlist.get(k).getReturnquantity():0));
												if((poItem.get(j).getInCount()!=null?poItem.get(j).getInCount():0)<poItem.get(j).getReturnJquantity()){
													throw new SyBaseException("错误:超出采购订单总入库数量");
												}else{
													logicPoItemDAO.updateLogicPoItemDO(poItem.get(j));
												}
											}
										}
									}
								logicPoReturnItemDAO.updateLogicPoReturnItemDO(lItemDO);
//								lpwitem.get(i).setReturnCount((lpwitem.get(i).getReturnCount()!=null?lpwitem.get(i).getReturnCount():0)+lItemDO.getBadcount());
//								lpwitem.get(i).setJreturnCount((lpwitem.get(i).getJreturnCount()!=null?lpwitem.get(i).getJreturnCount():0)+lItemDO.getJbadCount());
								lpwitem.get(i).setReturnCount(lItemDO.getBadcount());
								lpwitem.get(i).setJreturnCount(lItemDO.getJbadCount());
								
								
								if(lpwitem.get(i).getMaterialsid().equals(lItemDO.getMaterialsid())&&lpwitem.get(i).getCode().equals(lItemDO.getCode())&&lpwitem.get(i).getName().equals(lItemDO.getName())){
									LogicPoWareItemBatchDO poWareItemBatchDO = new LogicPoWareItemBatchDO();
									poWareItemBatchDO.setWareitemid(lpwitem.get(i).getId());
									poWareItemBatchDO.setCode(lpwitem.get(i).getCode());
									List<LogicPoWareItemBatchDO> logicPoWareItemBatchDO= logicPoWareItemBatchDAO.findListByExample(poWareItemBatchDO);
									if(lItemDO.getItemBatch() !=null && !"".equals(lItemDO.getItemBatch().trim())){
										List<LogicPoReturnItemBatchDO> batchDOs =JSONArray.parseArray(lItemDO.getItemBatch(), LogicPoReturnItemBatchDO.class);
										for (int j = 0; j < logicPoWareItemBatchDO.size(); j++) {
											for (int l = 0; l < batchDOs.size(); l++) {
												if(logicPoWareItemBatchDO.get(j).getCode().equals(batchDOs.get(l).getCode()) && logicPoWareItemBatchDO.get(j).getBatch().equals(batchDOs.get(l).getBatch()) && logicPoWareItemBatchDO.get(j).getState().equals(batchDOs.get(l).getState())){
													logicPoWareItemBatchDO.get(j).setJreturnCount((logicPoWareItemBatchDO.get(j).getJreturnCount()==null?0:logicPoWareItemBatchDO.get(j).getJreturnCount())+batchDOs.get(l).getJreturnquantity());
													logicPoWareItemBatchDO.get(j).setReturnCount((logicPoWareItemBatchDO.get(j).getReturnCount()==null?0:logicPoWareItemBatchDO.get(j).getReturnCount())+batchDOs.get(l).getReturnquantity());
												}
											}
											
											logicPoWareItemBatchDAO.updateLogicPoWareItemBatchDO(logicPoWareItemBatchDO.get(j));
//											System.out.println("sdsafffffffffff:"+JSONArray.toJSONString(logicPoWareItemBatchDO));
											lpwitem.get(i).setItemBatchDO(JSONArray.toJSONString(logicPoWareItemBatchDO));
											logicPoPoWareItemDAO.updateLogicPoWareItemDO(lpwitem.get(i));
										}
									}else{
										logicPoPoWareItemDAO.updateLogicPoWareItemDO(lpwitem.get(i));
									}
									
								}
								}
							}
							if((lpwitem.get(i).getJreturnCount()!=null?lpwitem.get(i).getJreturnCount():0)<lpwitem.get(i).getJquantity()){
								billstatus=false;
							}
					}
					if(billstatus){
						lpwlist.get(0).setBillstatus(Short.parseShort("5"));//全部退货
						logicPoWareDAO.updateLogicPoWareDO(lpwlist.get(0));
					}else{
						lpwlist.get(0).setBillstatus(Short.parseShort("4"));//部分退货
						logicPoWareDAO.updateLogicPoWareDO(lpwlist.get(0));
					}
				}
				if(lItemDO.getItemBatch() != null && !"".equals(lItemDO.getItemBatch().trim())){
					List<LogicPoReturnItemBatchDO> batchDOs =JSONArray.parseArray(lItemDO.getItemBatch(), LogicPoReturnItemBatchDO.class);
					if(batchDOs != null){
						for (LogicPoReturnItemBatchDO logicPoReturnItemBatchDO : batchDOs) {
							LogicWhAffDO lwhaff=new LogicWhAffDO();
							lwhaff.setPrice(axxlist.get(k).getPrice());
							lwhaff.setBillCode(curAP.getReturnpocode());
							lwhaff.setBillType("CT");
							lwhaff.setBatch(logicPoReturnItemBatchDO.getBatch());
							lwhaff.setWhCode(curAP.getWhcode());
							lwhaff.setUnit(axxlist.get(k).getUnit());
							lwhaff.setJunit(axxlist.get(k).getJunit());
							lwhaff.setWhCode(curAP.getWhcode());
							lwhaff.setHubName(curAP.getWhname());
							lwhaff.setStatus(logicPoReturnItemBatchDO.getState());
							lwhaff.setCode(axxlist.get(k).getCode());
							lwhaff.setName(axxlist.get(k).getName());
							lwhaff.setSpec(axxlist.get(k).getSpec());
							lwhaff.setQuantity(-logicPoReturnItemBatchDO.getReturnquantity());
							lwhaff.setJquantity(-logicPoReturnItemBatchDO.getJreturnquantity());
							logicWhAffStockService.updateWhAffstockQuantity(lwhaff, SessionUtil.getUser(request),false);
						}
					}
					
				}else{
						LogicWhAffDO lwhaff=new LogicWhAffDO();
						lwhaff.setPrice(axxlist.get(k).getPrice());
						lwhaff.setBillCode(curAP.getReturnpocode());
						lwhaff.setBillType("CT");
						lwhaff.setBatch("NoBatch");
						lwhaff.setWhCode(curAP.getWhcode());
						lwhaff.setUnit(axxlist.get(k).getUnit());
						lwhaff.setJunit(axxlist.get(k).getJunit());
						lwhaff.setWhCode(curAP.getWhcode());
						lwhaff.setHubName(curAP.getWhname());
						lwhaff.setStatus(axxlist.get(k).getState());
						lwhaff.setCode(axxlist.get(k).getCode());
						lwhaff.setName(axxlist.get(k).getName());
						lwhaff.setSpec(axxlist.get(k).getSpec());
						lwhaff.setQuantity(-axxlist.get(k).getReturnquantity());
						lwhaff.setJquantity(-axxlist.get(k).getJreturnquantity());
						logicWhAffStockService.updateWhAffstockQuantity(lwhaff, SessionUtil.getUser(request),false);
				}
				
				
					}	
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}

	@Override
	public Integer untreatedPoreturncode(Map<String, Object> map)
			throws SyBaseException {
		// TODO Auto-generated method stub
		return logicPoReturnDAO.untreatedPoreturncode(map);
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		// TODO Auto-generated method stub
		return null;
	}
}
